import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/cookie'

const state = {
  token: getToken(),
  name: '',
  userId: '',
  avatar: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  login({ commit }, loginInfo) {
    return new Promise((resolve, reject) => {
      login({ ...loginInfo })
        .then((res) => {
          const { data } = res
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token)
        .then((res) => {
          const { data } = res
          commit('SET_NAME', data.user_name)
          commit('SET_USERID', data.user_id)
          commit('SET_AVATAR', data.avatar)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USERID', '')
          removeToken()
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
